<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/bootstrap/dist/css/bootstrap.min.css">
    <style type="text/css">
        .container {
            padding-top: 150px;
        }
        
        .list-group {
            display: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="请输入搜索关键字" id="search">
            <ul class="list-group" id="list-box">

            </ul>
        </div>
    </div>
    <script src="/js/ajax.js">
    </script>
    <script src="/art-template/lib/template-web.js"></script>
    <script type="text/html" id="tpl">
        {{each result}}
        <li class="list-group-item">{{$value}}</li>
        {{/each}}
    </script>
    <script>
        //获取搜索框
        var searchInp = document.querySelector('#search');
        //获取提示文字的存放容器
        var listBox = document.querySelector('list-box');
        //存储定时器的变量
        var timer = null;
        //当用户在文本框输入时候触发
        searchInp.addEventListener('input', function() {
            //清除上一次开启的定时器
            clearTimeout(timer);
            //获取用户输入的内容
            var key = this.value;
            if (key.trim().length == 0) {
                listBox.style.display = 'none';
                return;
            }
            timer = setTimeout(function() {
                ajax({
                    type: 'get',
                    url: 'http://localhost:3000/searchAutoPrompt',
                    data: {
                        key: key
                    },
                    success: function(result) {
                        //使用模板引擎拼接字符串
                        var html = template('tpl', {
                                result: result
                            })
                            //将拼接好的字符串显示在页面中
                        listBox.innerHTML = html;
                        //显示ul容器
                        listBox.style.display = 'block';
                    }
                })
            }, 800)
        })
    </script>
</body>

</html>